package com.ruoyi.media.service.impl;

import com.ruoyi.media.mapper.MediaDashboardMapper;
import com.ruoyi.media.service.IMediaDashboardService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 广电用户仪表盘服务实现
 */
@Service
public class MediaDashboardServiceImpl implements IMediaDashboardService {

    @Autowired
    private MediaDashboardMapper mediaDashboardMapper;

    // 缓存仪表盘数据，避免频繁查询数据库
    private final ConcurrentHashMap<String, Object> dashboardCache = new ConcurrentHashMap<>();
    private long lastRefreshTime = 0;
    private static final long CACHE_DURATION = 5 * 60 * 1000; // 5分钟缓存

    @Override
    public Map<String, Object> getDashboardData() {
        // 检查缓存是否有效
        if (System.currentTimeMillis() - lastRefreshTime < CACHE_DURATION && dashboardCache.containsKey("dashboardData")) {
            return (Map<String, Object>) dashboardCache.get("dashboardData");
        }

        // 缓存失效，重新加载数据
        return refreshDashboardData();
    }

    @Override
    public Map<String, Object> refreshDashboardData() {
        Map<String, Object> dashboardData = new HashMap<>();

        try {
            // 1. 基础指标数据
            Map<String, Object> baseMetrics = mediaDashboardMapper.getBaseMetrics();
            int totalUsers = baseMetrics.get("totalUsers") != null ? (int) baseMetrics.get("totalUsers") : 0;
            int activeUsers = baseMetrics.get("activeUsers") != null ? (int) baseMetrics.get("activeUsers") : 0;
            double avgConsumption = baseMetrics.get("avgConsumption") != null ? (double) baseMetrics.get("avgConsumption") : 0.0;
            int pendingRetention = baseMetrics.get("pendingRetention") != null ? (int) baseMetrics.get("pendingRetention") : 0;

            // 计算活跃率
            double activeRate = totalUsers > 0 ? Math.round((double) activeUsers / totalUsers * 100 * 100) / 100.0 : 0.0;

            // 模拟用户增长率（实际项目中应从数据库计算）
            int lastMonthUsers = totalUsers - (int) (totalUsers * 0.1); // 假设上月用户数少10%
            double userGrowth = lastMonthUsers > 0 ? Math.round(((double) totalUsers - lastMonthUsers) / lastMonthUsers * 100 * 100) / 100.0 : 0.0;

            dashboardData.put("totalUsers", totalUsers);
            dashboardData.put("activeUsers", activeUsers);
            dashboardData.put("activeRate", activeRate);
            dashboardData.put("avgConsumption", Math.round(avgConsumption * 100) / 100.0);
            dashboardData.put("pendingRetention", pendingRetention);
            dashboardData.put("userGrowth", userGrowth);

            // 2. 业务品牌分布数据
            List<Map<String, Object>> businessBrandData = mediaDashboardMapper.getBusinessBrandDistribution();
            if (businessBrandData == null || businessBrandData.isEmpty()) {
                // 提供默认模拟数据
                businessBrandData = generateDefaultBusinessBrandData();
            }
            dashboardData.put("businessBrandData", businessBrandData);

            // 3. 用户价值等级分布数据
            List<Map<String, Object>> userValueData = mediaDashboardMapper.getUserValueDistribution();
            if (userValueData == null || userValueData.isEmpty()) {
                // 提供默认模拟数据
                userValueData = generateDefaultUserValueData();
            }
            dashboardData.put("userValueData", userValueData);

            // 4. 电视消费水平分布数据
            List<Map<String, Object>> tvConsumeData = mediaDashboardMapper.getTvConsumptionDistribution();
            if (tvConsumeData == null || tvConsumeData.isEmpty()) {
                // 提供默认模拟数据
                tvConsumeData = generateDefaultTvConsumeData();
            }
            dashboardData.put("tvConsumeData", tvConsumeData);

            // 5. 宽带消费水平分布数据
            List<Map<String, Object>> broadbandConsumeData = mediaDashboardMapper.getBroadbandConsumptionDistribution();
            if (broadbandConsumeData == null || broadbandConsumeData.isEmpty()) {
                // 提供默认模拟数据
                broadbandConsumeData = generateDefaultBroadbandConsumeData();
            }
            dashboardData.put("broadbandConsumeData", broadbandConsumeData);

            // 6. 用户增长趋势数据
            List<Map<String, Object>> growthTrendData = mediaDashboardMapper.getUserGrowthTrend();
            if (growthTrendData == null || growthTrendData.isEmpty()) {
                // 提供默认模拟数据
                growthTrendData = generateDefaultGrowthTrendData();
            }
            dashboardData.put("growthTrendData", growthTrendData);

            // 更新缓存
            dashboardCache.put("dashboardData", dashboardData);
            lastRefreshTime = System.currentTimeMillis();

        } catch (Exception e) {
            // 如果数据库查询失败，返回模拟数据
            dashboardData = generateMockDashboardData();
        }

        return dashboardData;
    }

    @Override
    public Map<String, Object> getDashboardDataByDateRange(String startDate, String endDate) {
        // 这里可以实现根据时间范围查询数据的逻辑
        // 目前暂时返回基础数据
        Map<String, Object> result = new HashMap<>();
        
        // 调用基础方法获取数据
        Map<String, Object> baseData = getDashboardData();
        result.putAll(baseData);
        
        // 添加时间范围信息
        result.put("startDate", startDate);
        result.put("endDate", endDate);
        
        return result;
    }

    // 生成默认的业务品牌分布数据
    private List<Map<String, Object>> generateDefaultBusinessBrandData() {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(createChartData("高清套餐", 4500));
        data.add(createChartData("宽带套餐", 3200));
        data.add(createChartData("融合套餐", 1800));
        data.add(createChartData("基础套餐", 500));
        return data;
    }

    // 生成默认的用户价值等级分布数据
    private List<Map<String, Object>> generateDefaultUserValueData() {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(createChartData("高价值用户", 2800));
        data.add(createChartData("中价值用户", 4200));
        data.add(createChartData("低价值用户", 3000));
        return data;
    }

    // 生成默认的电视消费水平分布数据
    private List<Map<String, Object>> generateDefaultTvConsumeData() {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(createChartData("低消费", 2500));
        data.add(createChartData("中消费", 3800));
        data.add(createChartData("高消费", 2700));
        data.add(createChartData("非常高", 1000));
        return data;
    }

    // 生成默认的宽带消费水平分布数据
    private List<Map<String, Object>> generateDefaultBroadbandConsumeData() {
        List<Map<String, Object>> data = new ArrayList<>();
        data.add(createChartData("低消费", 3200));
        data.add(createChartData("中消费", 4300));
        data.add(createChartData("高消费", 2500));
        return data;
    }

    // 生成默认的用户增长趋势数据
    private List<Map<String, Object>> generateDefaultGrowthTrendData() {
        List<Map<String, Object>> data = new ArrayList<>();
        String[] months = {"1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月"};
        int[] newUsers = {800, 750, 900, 850, 1000, 950, 1100, 1050, 1200, 1150, 1300, 1250};
        
        int total = 0;
        for (int i = 0; i < months.length; i++) {
            total += newUsers[i];
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", months[i]);
            monthData.put("newUsers", newUsers[i]);
            monthData.put("totalUsers", total);
            data.add(monthData);
        }
        return data;
    }

    // 生成完整的模拟仪表盘数据
    private Map<String, Object> generateMockDashboardData() {
        Map<String, Object> data = new HashMap<>();
        data.put("totalUsers", 10000);
        data.put("activeUsers", 8500);
        data.put("activeRate", 85.0);
        data.put("avgConsumption", 128.50);
        data.put("pendingRetention", 320);
        data.put("userGrowth", 12.5);
        data.put("businessBrandData", generateDefaultBusinessBrandData());
        data.put("userValueData", generateDefaultUserValueData());
        data.put("tvConsumeData", generateDefaultTvConsumeData());
        data.put("broadbandConsumeData", generateDefaultBroadbandConsumeData());
        data.put("growthTrendData", generateDefaultGrowthTrendData());
        return data;
    }

    // 创建图表数据项
    private Map<String, Object> createChartData(String name, int value) {
        Map<String, Object> data = new HashMap<>();
        data.put("name", name);
        data.put("value", value);
        return data;
    }
}